<template>
  <div class="workspace-container">
    <!-- 欢迎卡片 -->
    <el-card class="welcome-card">
      <div class="welcome-content">
        <div class="user-avatar">
          <el-avatar :size="80" :src="userInfo.avatar || defaultAvatar" />
        </div>
        <div class="welcome-text">
          <h2>欢迎回来，{{ userInfo.name || '用户' }}</h2>
          <p>今天是 {{ currentDate }}，祝您工作愉快！</p>
        </div>
        <!-- 添加导出报表按钮 -->
        <div class="export-button" v-if="isAdmin">
          <el-button type="primary" @click="handleExportReport">
            <el-icon><Download /></el-icon> 导出违法类型分布表
          </el-button>
        </div>
      </div>
    </el-card>
    
    <!-- 快捷操作区 -->
    <el-row :gutter="20" class="quick-actions">
      <el-col :span="8" v-for="action in quickActions" :key="action.name">
        <el-card shadow="hover" class="action-card" @click="handleActionClick(action.route)">
          <div class="action-content">
            <el-icon :size="40" :color="action.color">
              <component :is="action.icon" />
            </el-icon>
            <div class="action-text">
              <div class="action-title">{{ action.title }}</div>
              <div class="action-desc">{{ action.description }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 统计信息区 -->
    <el-row :gutter="20" class="stats-row">
      <!-- 我的违法记录 -->
      <el-col :span="12">
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>我的违法记录</span>
              <el-button type="text" @click="router.push('/my-violations')">查看全部</el-button>
            </div>
          </template>
          <div class="stats-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ stats.totalViolations }}</div>
                  <div class="stat-label">总违法记录</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ stats.pendingViolations }}</div>
                  <div class="stat-label">未处理</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ stats.appealingViolations }}</div>
                  <div class="stat-label">申诉中</div>
                </div>
              </el-col>
            </el-row>
            
            <!-- 最近违法记录 -->
            <div class="recent-violations">
              <h4>最近违法记录</h4>
              <el-empty v-if="recentViolations.length === 0" description="暂无违法记录" />
              <el-table
                v-else
                :data="recentViolations"
                style="width: 100%"
                :show-header="false"
              >
                <el-table-column width="120">
                  <template #default="scope">
                    <el-tag :type="getViolationTypeTag(scope.row.type)" size="small">
                      {{ getViolationTypeName(scope.row.type) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="location" />
                <el-table-column prop="date" width="100" />
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 我的申诉 -->
      <el-col :span="12">
        <el-card class="stats-card">
          <template #header>
            <div class="card-header">
              <span>我的申诉</span>
              <el-button type="text" @click="router.push('/appeal')">查看全部</el-button>
            </div>
          </template>
          <div class="stats-content">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ stats.totalAppeals }}</div>
                  <div class="stat-label">总申诉</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ stats.pendingAppeals }}</div>
                  <div class="stat-label">处理中</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ stats.approvedAppeals }}</div>
                  <div class="stat-label">已通过</div>
                </div>
              </el-col>
            </el-row>
            
            <!-- 最近申诉 -->
            <div class="recent-appeals">
              <h4>最近申诉</h4>
              <el-empty v-if="recentAppeals.length === 0" description="暂无申诉记录" />
              <el-table
                v-else
                :data="recentAppeals"
                style="width: 100%"
                :show-header="false"
              >
                <el-table-column width="120">
                  <template #default="scope">
                    <el-tag :type="getAppealStatusTag(scope.row.status)" size="small">
                      {{ getAppealStatusName(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="reason" :show-overflow-tooltip="true" />
                <el-table-column prop="date" width="100" />
              </el-table>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 通知公告 -->
    <el-card class="notice-card">
      <template #header>
        <div class="card-header">
          <span>通知公告</span>
        </div>
      </template>
      <div class="notice-content">
        <el-timeline>
          <el-timeline-item
            v-for="(notice, index) in notices"
            :key="index"
            :timestamp="notice.date"
            :type="notice.type"
          >
            {{ notice.content }}
          </el-timeline-item>
        </el-timeline>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/store/user'
import { Document, Bell, User, Calendar, Warning, ChatDotRound, Download } from '@element-plus/icons-vue'
import { getViolationStatistics, getViolationPie, exportViolationReport } from '@/api/dashboard'
import { getViolationPage } from '@/api/violation'
import { getUserAppealPage } from '@/api/appeal'

const router = useRouter()
const userStore = useUserStore()

// 用户信息
const userInfo = computed(() => userStore.userInfo || {})
const defaultAvatar = 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'

// 当前日期
const currentDate = computed(() => {
  const now = new Date()
  return `${now.getFullYear()}年${now.getMonth() + 1}月${now.getDate()}日`
})

// 快捷操作
const quickActions = [
  {
    title: '我的违法记录',
    description: '查看个人违法记录',
    icon: 'Document',
    color: '#f56c6c',
    route: '/my-violations'
  },
  {
    title: '申诉管理',
    description: '管理我的申诉',
    icon: 'ChatDotRound',
    color: '#e6a23c',
    route: '/appeal'
  },
  {
    title: '个人中心',
    description: '管理个人信息',
    icon: 'User',
    color: '#409eff',
    route: '/profile'
  }
]

// 统计数据
const stats = reactive({
  totalViolations: 0,
  pendingViolations: 0,
  appealingViolations: 0,
  totalAppeals: 0,
  pendingAppeals: 0,
  approvedAppeals: 0
})

// 最近违法记录
const recentViolations = ref([])

// 最近申诉
const recentAppeals = ref([])

// 通知公告
const notices = ref([])

// 处理操作点击
const handleActionClick = (route) => {
  router.push(route)
}

// 获取违法类型名称
const getViolationTypeName = (type) => {
  const typeMap = {
    'runred': '闯红灯',
    'overspeed': '超速',
    'other': '其他违法'
  }
  return typeMap[type] || '未知类型'
}

// 获取违法类型标签样式
const getViolationTypeTag = (type) => {
  const tagMap = {
    'runred': 'danger',
    'overspeed': 'warning',
    'other': 'info'
  }
  return tagMap[type] || ''
}

// 获取申诉状态名称
const getAppealStatusName = (status) => {
  const statusMap = {
    '0': '待处理',
    '1': '已通过',
    '2': '已驳回'
  }
  return statusMap[status] || '未知状态'
}

// 获取申诉状态标签样式
const getAppealStatusTag = (status) => {
  const tagMap = {
    '0': 'info',
    '1': 'success',
    '2': 'danger'
  }
  return tagMap[status] || ''
}

// 获取数据
const fetchData = async () => {
  try {
    // 调用API获取数据
    // 1. 获取违法记录统计
    const violationStatsResponse = await getViolationStatistics({}, 3); // 3表示普通用户角色
    if (violationStatsResponse.code === 200 && violationStatsResponse.data) {
      const violationData = violationStatsResponse.data;
      // 修改这里，使用正确的字段名 totalViolation
      stats.totalViolations = parseInt(violationData.totalViolation) || 0;
      // 这两个字段后端没有返回，暂时设为0或从其他接口获取
      stats.pendingViolations = 0;
      stats.appealingViolations = 0;
    }
    
    // 2. 获取申诉统计
    const appealStatsResponse = await getViolationPie({}, 3); // 3表示普通用户角色
    if (appealStatsResponse.code === 200 && appealStatsResponse.data) {
      const appealData = appealStatsResponse.data;
      // 修改这里，waitWarning表示待处理申诉
      stats.pendingAppeals = parseInt(appealData.waitWarning) || 0;
      // 总申诉数和已通过申诉数后端没有直接提供，可以暂时设为0
      // 或者通过其他接口获取
      stats.totalAppeals = 0;
      stats.approvedAppeals = 0;
    }
    
    // 3. 获取最近违法记录
    const violationPageResponse = await getViolationPage({pageSize: 2, page: 1}, false);
    if (violationPageResponse.code === 200 && violationPageResponse.data && violationPageResponse.data.records) {
      recentViolations.value = violationPageResponse.data.records.map(item => ({
        type: item.violationType === 1 ? 'runred' : 
              item.violationType === 2 ? 'overspeed' : 'other',
        location: item.location || '未知位置',
        date: item.createTime ? item.createTime.split(' ')[0] : '未知日期'
      }));
    }
    
    // 4. 获取最近申诉
    const appealPageResponse = await getUserAppealPage({pageSize: 2, page: 1});
    if (appealPageResponse.code === 200 && appealPageResponse.data && appealPageResponse.data.records) {
      recentAppeals.value = appealPageResponse.data.records.map(item => ({
        status: item.status || '0',
        reason: item.reason || '未提供原因',
        date: item.createTime ? item.createTime.split(' ')[0] : '未知日期'
      }));
    }
    
    // 通知公告可以保留模拟数据，或者添加新的API调用获取
    notices.value = [
      { content: '系统升级通知：本系统将于6月30日进行升级维护，届时可能会有短暂服务中断', date: '2023-06-20', type: 'warning' },
      { content: '新功能上线：现在您可以通过手机APP查看违法记录和提交申诉', date: '2023-06-15', type: 'success' },
      { content: '温馨提示：请遵守交通规则，安全出行', date: '2023-06-01', type: 'info' }
    ];
    
  } catch (error) {
    console.error('获取工作台数据失败:', error);
  }
}

onMounted(() => {
  fetchData()
})

// 判断是否为管理员
const isAdmin = computed(() => {
  const role = userStore.userInfo?.role
  return role === '1' || role === '2' // 1和2分别代表管理员和系统管理员
})

// 处理导出报表
const handleExportReport = () => {
  exportViolationReport()
}
</script>

<style scoped>
.workspace-container {
  padding: 20px;
}

.welcome-card {
  margin-bottom: 20px;
}

.welcome-content {
  display: flex;
  align-items: center;
  position: relative; /* 添加相对定位 */
}

.export-button {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

.user-avatar {
  margin-right: 20px;
}

.welcome-text h2 {
  margin: 0 0 10px 0;
  font-size: 24px;
}

.welcome-text p {
  margin: 0;
  color: #909399;
}

.quick-actions {
  margin-bottom: 20px;
}

.action-card {
  cursor: pointer;
  transition: all 0.3s;
}

.action-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.action-content {
  display: flex;
  align-items: center;
}

.action-text {
  margin-left: 15px;
}

.action-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.action-desc {
  color: #909399;
  font-size: 14px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.stat-item {
  text-align: center;
  padding: 10px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
}

.stat-label {
  color: #909399;
  font-size: 14px;
}

.recent-violations,
.recent-appeals {
  margin-top: 20px;
}

.recent-violations h4,
.recent-appeals h4 {
  margin-bottom: 10px;
  font-size: 16px;
  color: #606266;
}

.notice-content {
  padding: 0 20px;
}
</style>